package ext.acae2.document.helper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import wt.doc.WTDocument;
import wt.fc.ObjectIdentifier;
import wt.fc.PersistInfo;
import wt.fc.Persistable;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.lifecycle.State;
import wt.log4j.LogR;
import wt.pds.StatementSpec;
import wt.query.ClassAttribute;
import wt.query.ConstantExpression;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.type.TypeDefinitionForeignKey;
import wt.type.TypeDefinitionReference;
import wt.util.WTException;
import wt.util.WTMessage;
import wt.util.WTProperties;
import wt.vc.IterationInfo;
import wt.vc.VersionControlHelper;

import com.ptc.core.components.util.OidHelper;
import com.ptc.core.meta.type.mgmt.server.impl.WTTypeDefinition;

import ext.acae2.document.mvc.ECMReplyDocBean;
import ext.acae2.document.mvc.builders.ECMRecommendTableBuilder;
import ext.acae2.document.resource.DocResource;
import ext.acae2.util.IBAHelper;
import ext.acae2.util.ReportExcelGenerateUtil;

/**
 * @desription ECM 工程协调单的关联
 * @author cnie
 * @date 2013-7-15 下午4:15:38
 */
public class ECMDocHelper {

	private static final String RESOURCE = DocResource.class.getName();
	
	private static final Logger LOGGER = LogR.getLogger(ECMDocHelper.class.getName());

	private static final String NONEEDREPLYSTATE = WTMessage
			.getLocalizedMessage(RESOURCE, DocResource.WUXUDAFU_VIEW_NAME,
					null, Locale.SIMPLIFIED_CHINESE);

	private static final String REPLIEDSTATE = WTMessage.getLocalizedMessage(
			RESOURCE, DocResource.YUDAFU_VIEW_NAME, null,
			Locale.SIMPLIFIED_CHINESE);

	private static final String NOTREPLYSTATE = WTMessage.getLocalizedMessage(
			RESOURCE, DocResource.WEIDAFU_VIEW_NAME, null,
			Locale.SIMPLIFIED_CHINESE);
	
	private static String wttemp;
	private static String fromPath;
	private static String wthome;
	static{
		try {
			wthome = WTProperties.getLocalProperties().getProperty(
					"wt.home");
			wttemp = WTProperties.getLocalProperties().getProperty(
					"wt.temp");
			fromPath = wthome+File.separator+"codebase"+File.separator+"ext"+File.separator+"acae2"+File.separator
					+"conf/ECMReportTemplate.xls";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @description 获取所有的ECM文档
	 * @author cnie
	 * @date 2013-7-15 下午4:18:53
	 * @version 1.0
	 * @param params
	 * @return
	 * @throws WTException
	 */
	public static Map<WTDocument, ECMReplyDocBean> getALLECMDoc(Map<String, Object> params)
			throws Exception {
		long startTime = System.currentTimeMillis();
//		List<WTDocument> ecmDocs = new ArrayList<WTDocument>();
		Map<WTDocument, ECMReplyDocBean> ecmReportMap = new HashMap<WTDocument, ECMReplyDocBean>();
		String wtTypeName = "com.acae.ECM;com.acae.externalECM";// 工程协调单、外部工程协调单
		// 页面参数

		QuerySpec qs = new QuerySpec();
		int a = qs.appendClassList(WTDocument.class, true);
		int b = qs.appendClassList(WTTypeDefinition.class, false);
		qs.setAdvancedQueryEnabled(true);
		SearchCondition typeRefSc = new SearchCondition(WTDocument.class,
				WTDocument.TYPE_DEFINITION_REFERENCE + "."
						+ TypeDefinitionReference.KEY + "."
						+ TypeDefinitionForeignKey.BRANCH_ID, WTTypeDefinition.class,
				WTTypeDefinition.ITERATION_INFO + "."
						+ IterationInfo.BRANCH_ID);
		qs.appendWhere(typeRefSc, new int[] { a, b });
		ClassAttribute typeNameAttr = new ClassAttribute(
				WTTypeDefinition.class, WTTypeDefinition.NAME);
		SearchCondition wtTypeCondition = new SearchCondition(typeNameAttr,
				SearchCondition.IN,
				wt.query.ArrayExpression.newArrayExpression(wtTypeName, ";",
						true));
		qs.appendAnd();
		qs.appendWhere(wtTypeCondition, new int[] { b });
		qs.appendAnd();
		SearchCondition lastestSc = new SearchCondition(WTTypeDefinition.class,
				WTTypeDefinition.ITERATION_INFO + "." + IterationInfo.LATEST,
				"TRUE");
		qs.appendWhere(lastestSc, new int[] { b });

		qs.appendAnd();
		SearchCondition stateSc = new SearchCondition(WTDocument.class,
				WTDocument.LIFE_CYCLE_STATE, SearchCondition.EQUAL, "RELEASED");
		qs.appendWhere(stateSc, new int[] { a });

		// if(startime!=null){
		// qs.appendAnd();
		// SearchCondition starttimeSc = new
		// SearchCondition(WTDocument.class,WTDocument.MODIFY_TIMESTAMP,
		// SearchCondition.GREATER_THAN,startime);
		// qs.appendWhere(starttimeSc, new int[] { a });
		// }
		// if(endtime!=null){
		// qs.appendAnd();
		// SearchCondition endtimeSc = new
		// SearchCondition(WTDocument.class,WTDocument.MODIFY_TIMESTAMP,
		// SearchCondition.LESS_THAN,endtime);
		// qs.appendWhere(endtimeSc, new int[] { a });
		// }

		QueryResult qr = PersistenceHelper.manager.find((StatementSpec) qs);
		// LatestConfigSpec lastestConfig =new LatestConfigSpec();
		// lastestConfig.process(qr);
		while (qr.hasMoreElements()) {
			Object obj = qr.nextElement();
			if (obj instanceof Persistable[]) {
				Persistable[] pArr = (Persistable[]) obj;
				WTDocument doc = (WTDocument) pArr[0];
				if (VersionControlHelper.isLatestIteration(doc)) {
					ECMReplyDocBean ecmReplyDocBean = new ECMReplyDocBean();
					ecmReplyDocBean.setECMDocOid(OidHelper.getNmOid(doc).toString());
					ecmReplyDocBean.setECMName(doc.getName());
					ecmReplyDocBean.setECMNumber(doc.getNumber().trim());
					ecmReplyDocBean.setModifyTimestamp(doc.getModifyTimestamp());
					boolean isReplyRequired = IBAHelper.getIBABooleanValue(
							doc, "isReplyRequired"); // 是否需要答复
					ecmReplyDocBean.setReplyRequired(isReplyRequired);
					String replyDocNumber = IBAHelper.getIBAStringValue(doc,
							"replyDocID"); // 所答复的ECM的编号
					if (StringUtils.isNotBlank(replyDocNumber)) {
						replyDocNumber = replyDocNumber.trim();
						int index = replyDocNumber.indexOf("(");
						if (index > -1)
							replyDocNumber = replyDocNumber.substring(0, index);
					}
					ecmReplyDocBean.setECMIsRepliedNumber(replyDocNumber);
					ecmReportMap.put(doc, ecmReplyDocBean);
				}

			}
		}
		LOGGER.debug("getALLECMDOC=======================>"+(System.currentTimeMillis()-startTime));
		return ecmReportMap;
	}

	/**
	 * 
	 * @description 获取有效的ECM文档对象
	 * @author cnie
	 * @date 2013-7-17 下午2:57:57
	 * @version 1.0
	 * @param params
	 *            页面的查询参数
	 * @param allEcmDocs
	 *            所有的ECM文档对象
	 * @return
	 * @throws Exception
	 */
	public static List<WTDocument> getAvailableECMDoc(
			Map<String, Object> params, Set<WTDocument> allEcmDocs)
			throws Exception {
		List<WTDocument> availableEcmDocs = new ArrayList<WTDocument>();
		Timestamp startime = (Timestamp) params
				.get(ECMRecommendTableBuilder.PARAM_START_TIME);
		Timestamp endtime = (Timestamp) params
				.get(ECMRecommendTableBuilder.PARAM_END_TIME);
		//StringBuffer ecmNumSb = new StringBuffer("");
		String bianzhiDeptCode = (String) params
				.get(ECMRecommendTableBuilder.PARAM_SEND_DEPARTMENT);
		String receiveDeptCode = (String) params
				.get(ECMRecommendTableBuilder.PARAM_RECEIVE_DEPARTMENT);
//		if (StringUtils.isNotBlank(bianzhiDeptCode)) {
//			ecmNumSb.append("ECM-"+bianzhiDeptCode);
//		}
//		if (StringUtils.isNotBlank(receiveDeptCode)) {
//			ecmNumSb.append("-");
//			ecmNumSb.append(receiveDeptCode);
//		}
		for (WTDocument ecmDoc : allEcmDocs) {
			String ecmNumber = ecmDoc.getNumber();
			Timestamp modifyTimestamp = ecmDoc.getModifyTimestamp();
			if (startime != null) {
				if (modifyTimestamp.getTime() < startime.getTime()) {
					continue;
				}
			}
			if (endtime != null) {
				if (modifyTimestamp.getTime() > endtime.getTime()) {
					continue;
				}
			}
			if (StringUtils.isNotBlank(bianzhiDeptCode)) {
				if (ecmNumber.indexOf("ECM-"+bianzhiDeptCode) < 0) {
					continue;
				}
			}
			if (StringUtils.isNotBlank(receiveDeptCode)) {
				ecmNumber = ecmNumber.substring(0,ecmNumber.lastIndexOf("-"));
				if(!ecmNumber.endsWith(receiveDeptCode)){
					continue;
				}
			}
//			if (StringUtils.isNotBlank(ecmNumSb.toString())) {
//				if (ecmNumber.indexOf(ecmNumSb.toString()) < 0) {
//					continue;
//				}
//			}
			availableEcmDocs.add(ecmDoc);
		}
		return availableEcmDocs;
	}

	/***
	 * 
	 * @description 获取所有的符合查询条件的ECM文档
	 * @author cnie
	 * @date 2013-7-17 下午3:40:09
	 * @version 1.0
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static Object[] getALLAvailableEcmDoc(Map<String, Object> params)
			throws Exception {
		Map<WTDocument, ECMReplyDocBean> allEcmReportMap = getALLECMDoc(params);
		List<WTDocument> availableEcmDocs = getAvailableECMDoc(params,
				allEcmReportMap.keySet());
		List<ECMReplyDocBean> availableEcmBeans = new ArrayList<ECMReplyDocBean>();
		for (WTDocument availableEcmDoc : availableEcmDocs) {
			ECMReplyDocBean availableEcmBean = allEcmReportMap.get(availableEcmDoc);
			String availableEcmDocNum = availableEcmBean.getECMNumber();
			if (!availableEcmBean.isReplyRequired()) {
				availableEcmBean.setECMReplyDocOid("");
				availableEcmBean.setECMReplyNumber("");
				availableEcmBean.setECMReplyState(NONEEDREPLYSTATE);
			} else {
				WTDocument replyEcmDoc = null;
				Set<WTDocument> allEcmDocuments = allEcmReportMap.keySet();
				for (WTDocument ecmDoc : allEcmDocuments) {
					String replyDocNumber = allEcmReportMap.get(ecmDoc).getECMIsRepliedNumber();
					if (availableEcmDocNum.equals(replyDocNumber)){
						replyEcmDoc = ecmDoc;
						break;
					}
				}
				if (replyEcmDoc != null) {
					availableEcmBean.setECMReplyDocOid(OidHelper.getNmOid(
							replyEcmDoc).toString());
					availableEcmBean.setECMReplyNumber(replyEcmDoc.getNumber());
					availableEcmBean.setECMReplyState(REPLIEDSTATE);
				} else {
					availableEcmBean.setECMReplyDocOid("");
					availableEcmBean.setECMReplyNumber("");
					availableEcmBean.setECMReplyState(NOTREPLYSTATE);
				}
			}
			availableEcmBeans.add(availableEcmBean);
		}
		return new Object[] { availableEcmDocs, availableEcmBeans };
	}

	/**
	 * 
	 * @description 获取符合查询条件的未答复的ECM文档
	 * @author cnie
	 * @date 2013-7-17 下午3:24:59
	 * @version 1.0
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static Object[] getNotReplyEcmDoc(Map<String, Object> params)
			throws Exception {
		Map<WTDocument, ECMReplyDocBean> allEcmReportMap = getALLECMDoc(params);
		List<WTDocument> availableEcmDocs = getAvailableECMDoc(params,
				allEcmReportMap.keySet());
		List<WTDocument> notReplyECMDocs = new ArrayList<WTDocument>();
		List<ECMReplyDocBean> ecmReplyDocBeans = new ArrayList<ECMReplyDocBean>();

		for (WTDocument availableEcmDoc:availableEcmDocs) {
			ECMReplyDocBean availableEcmBean = allEcmReportMap.get(availableEcmDoc);
			
			String availableEcmDocNum = availableEcmBean.getECMNumber();
			boolean isReplyRequired = availableEcmBean.isReplyRequired();
			if (!isReplyRequired) {
				continue;
			}
			boolean isReplyFlag = false;
			Set<WTDocument> allEcmDocs = allEcmReportMap.keySet();
			for (WTDocument ecmDoc : allEcmDocs) {
				String replyDocNumber = allEcmReportMap.get(ecmDoc).getECMIsRepliedNumber();
				if (availableEcmDocNum.equals(replyDocNumber)){
					isReplyFlag = true;
					break;
				}
			}
			if (!isReplyFlag) {
				availableEcmBean.setECMReplyState(NOTREPLYSTATE);
				availableEcmBean.setECMReplyNumber("");
				availableEcmBean.setECMReplyDocOid("");
				ecmReplyDocBeans.add(availableEcmBean);
				notReplyECMDocs.add(availableEcmDoc);
			}
		}

		return new Object[] { notReplyECMDocs, ecmReplyDocBeans };
	}

	/***
	 * 
	 * @description 获取符合查询条件的已经答复的ECM文档
	 * @author cnie
	 * @date 2013-7-17 下午3:07:11
	 * @version 1.0
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static Object[] getRepliedECMDoc(Map<String, Object> params)
			throws Exception {
		Map<WTDocument, ECMReplyDocBean> allEcmReportMap = getALLECMDoc(params);
		List<WTDocument> availableEcmDocs = getAvailableECMDoc(params,
				allEcmReportMap.keySet());
		List<WTDocument> repliedECMDocs = new ArrayList<WTDocument>();
		List<ECMReplyDocBean> ecmReplyDocBeans = new ArrayList<ECMReplyDocBean>();
		for (WTDocument availableEcmDoc : availableEcmDocs) {
			ECMReplyDocBean availableEcmBean = allEcmReportMap.get(availableEcmDoc);
			String availableEcmDocNum = availableEcmBean.getECMNumber().trim();
			boolean isReplyRequired = availableEcmBean.isReplyRequired();
			if (!isReplyRequired) {
				continue;
			}
			Set<WTDocument> allEcmDocs = allEcmReportMap.keySet();
			for (WTDocument ecmDoc : allEcmDocs) {
				String replyDocNumber =  allEcmReportMap.get(ecmDoc).getECMIsRepliedNumber();
				if (availableEcmDocNum.equals(replyDocNumber)) {
					availableEcmBean.setECMReplyState(REPLIEDSTATE);
					availableEcmBean.setECMReplyNumber(ecmDoc.getNumber());
					availableEcmBean.setECMReplyDocOid(OidHelper.getNmOid(
							ecmDoc).toString());
					ecmReplyDocBeans.add(availableEcmBean);
					repliedECMDocs.add(availableEcmDoc);
					break;
				}	
			}
		}
		return new Object[] { repliedECMDocs, ecmReplyDocBeans };
	}

	/***
	 * 
	 * @description 获取符合查询条件的无需答复的ECM文档
	 * @author cnie
	 * @date 2013-7-17 下午3:06:44
	 * @version 1.0
	 * @param params
	 * @return
	 * @throws Exception
	 */
	public static Object[] getWUXUDAECMDoc(Map<String, Object> params)
			throws Exception {
		Map<WTDocument, ECMReplyDocBean> allEcmReportMap= getALLECMDoc(params);
		List<WTDocument> availableEcmDocs = getAvailableECMDoc(params,
				allEcmReportMap.keySet());
		List<WTDocument> noNeedReplyECMDocs = new ArrayList<WTDocument>();
		List<ECMReplyDocBean> ecmReplyDocBeans = new ArrayList<ECMReplyDocBean>();
		for (WTDocument availableEcmDoc : availableEcmDocs) {
			ECMReplyDocBean availableEcmBean = allEcmReportMap.get(availableEcmDoc);
			boolean isReplyRequired = availableEcmBean.isReplyRequired();
			if (!isReplyRequired) {
				availableEcmBean.setECMReplyDocOid("");
				availableEcmBean.setECMReplyNumber("");
				availableEcmBean.setECMReplyState(NONEEDREPLYSTATE);
				ecmReplyDocBeans.add(availableEcmBean);
				noNeedReplyECMDocs.add(availableEcmDoc);
			}
		}
		return new Object[] { noNeedReplyECMDocs, ecmReplyDocBeans };
	}
	
	public static String exportECMDetailToExcel(List<ECMReplyDocBean> ecmBeans) throws Exception {
		File toDir = new File(wttemp);
		if (!toDir.exists())
			toDir.mkdirs();
		long time = System.currentTimeMillis();
		String toPath = toDir + File.separator + "ecmReportInfo_" + time
				+ ".xls";
		ReportExcelGenerateUtil rgu = new ReportExcelGenerateUtil(fromPath);
		// 设置第一个Sheet
		HSSFWorkbook workbook = rgu.getWb();
		if (rgu.getSheet() == null) {
			throw new WTException("Excel Template Not Exists!");
		}
		workbook.setSheetName(0, "ecmReportInfo");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		int m = 1;
		for (ECMReplyDocBean ecmBean : ecmBeans) {
			Timestamp modifyTimestamp = ecmBean.getModifyTimestamp();
			String modifyTimeStr = sdf.format(modifyTimestamp.getTime());
			rgu.setStringValue(m, 0, ecmBean.getECMNumber());
			rgu.setStringValue(m, 1, ecmBean.getECMName());
			rgu.setStringValue(m, 2, modifyTimeStr);
			rgu.setStringValue(m, 3, ecmBean.getECMReplyState());
			rgu.setStringValue(m, 4, ecmBean.getECMReplyNumber());
			m++;
		}

		try {
			FileOutputStream fos = new FileOutputStream(toPath);
			workbook.write(fos);
			fos.close();
		} catch (Exception e) {
			LOGGER.error(e, e);
		}
		return toPath;
	}
	
	public static List<String> getDepartments(){
		List<String> departments = new ArrayList<String>();
		departments.add("");
		departments.add("131614-中航工业614所");
		departments.add("131624-中航工业624所");
		departments.add("131606-中航工业606所");
		departments.add("131608-中航工业608所");
		return departments;
	}

	public static void main(String[] args) throws Exception {
		// getReplyECMDoc(null);
		// getECMDoc(null);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		String startTime = "2013/07/16 18:15:30";
		sdf.setLenient(false);
		Timestamp ts = new Timestamp(sdf.parse(startTime).getTime());
		System.out.println(ts.toString());
	}

}
